package com.example.service;

import com.example.entity.chat.AiChat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatAiService {

    private static final String ApiSecretKey = "1ba8e610d04cfeccb2535824ac57f4e0.kCCMgr4MOJXeLyui"; // 替换为你的API密钥
    private static final String requestIdTemplate = "requestId_%d";
    private static final ObjectMapper mapper = new ObjectMapper();

    static ClientV4 client = new ClientV4.Builder(ApiSecretKey).build();

    public static String testInvoke(AiChat aiChat){
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), aiChat.getContent());
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        //调用模型
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        //获取响应数据
        JsonNode data=invokeModelApiResp.getData();

        //获取对应节点数据
        JsonNode choices=data.get("choices");
        JsonNode firstChoice=choices.get(0);
        JsonNode message=firstChoice.get("message");
        String content =message.get("content").asText();

        try {
            System.out.println("model output:" + mapper.writeValueAsString(invokeModelApiResp));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }
}